package top.dark.transaction;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * Author: Darkn
 * description:
 * Create Time: 2021/5/4 20:11
 */
public class JmsConsumer {
    private final static String ACTIVEMQ_URL = "tcp://192.168.136.181:61616";
    private final static String ACTIVEMQ_QUEUE = "transaction_queue";
    public static void main(String[] args) throws JMSException, IOException {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        Connection connection = factory.createConnection();
        connection.start();
        // true表示开启事务
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(ACTIVEMQ_QUEUE);
        MessageConsumer consumer = session.createConsumer(queue);
        consumer.setMessageListener(message -> {
            TextMessage textMessage = (TextMessage) message;
            try {
                if (textMessage.getText().equals("3")) {
                    double a = Integer.parseInt(textMessage.getText()) / 0;
                }
                System.out.println("transaction_queue消费数据：" + textMessage.getText());
                session.commit();
            } catch (JMSException e) {
                System.out.println("出现异常，消费失败，放弃消费");
                try {
                    session.rollback();
                } catch (JMSException ex) {
                    ex.printStackTrace();
                }
            }
        });
        System.in.read();
        consumer.close();
        connection.close();
    }
}
